<template>
  <div>
      <div>
        <div class="row-spaceb mg20">
          <p class="fwbold fs-md">· 服务补贴申请兑付</p>
          <el-button type="primary" size="medium" plain @click="$router.back()">返回</el-button>
        </div>
        <el-divider></el-divider>
        <div class="card">
          <!--          时间线-->
          <el-steps :active="detailStep" class="mg30 ml80 mr80" align-center finish-status="success">
            <el-step title="服务商申请"></el-step>
            <el-step title="等待审核"></el-step>
            <el-step :title="SubsidyApplyDetail?.status === 3 ? '申请失败' : '申请成功'"></el-step>
          </el-steps>
        <!-- 添加退回修改理由显示 -->
        <div v-if="SubsidyApplyDetail?.status === 4" class="mt20 mb20 pl10 pr10">
          <el-alert
            title="申请已退回修改"
            type="warning"
            :closable="false">
            <div>退回理由：{{ SubsidyApplyDetail.comment || '无' }}</div>
          </el-alert>
        </div>
          <!--          订单信息-->
          <div class="mt20">
            <div class="mg20 fs-md fwbold">· 订单信息</div>
            <el-table size="medium" v-loading="viewBtnLoading" :data="orderList" border  :header-cell-style="{background:'rgb(252, 241, 231)',color:'#606266'}">
              <el-table-column prop="orderId" label="订单编号" align="center"></el-table-column>
              <el-table-column prop="productName" label="服务产品名称" align="center"></el-table-column>
              <el-table-column prop="companyName" label="服务企业" align="center"></el-table-column>
              <el-table-column prop="finishTime" label="服务完成时间" align="center">
                <template slot-scope="{ row }">
                  {{ moment(row.finishTime).format('YYYY-MM-DD HH:mm:ss') }}
                </template>
              </el-table-column>
              <el-table-column prop="price" label="合同金额(元)" align="center">
                <template slot-scope="scope">
                  {{ scope.row.orderType === 2 ? $priceToThousands(scope.row.totalPrice) : $priceToThousands(scope.row.price) }}
                </template>
              </el-table-column>
              <el-table-column prop="bidamount" label="拟兑付金额(元)" align="center">
                <template slot-scope="scope">
                  {{ $priceToThousands(scope.row.discountPrice) }}
                </template>
              </el-table-column>
              <el-table-column label="服务状态" align="center">
                <template slot-scope="scope">
                  <span v-if="scope.row.status == 7">已完成</span>
                </template>
              </el-table-column>
            </el-table>
          </div>
            <!-- 经济效益信息（所有产品类型都需要） -->
            <div class="mt20">
              <div class="row-start-col-center">
                <div class="fs14 fwbold ml10">经济效益信息</div>
              </div>
              <div class="pl20 pr20 pt20">
                <el-form ref="economicForm" :model="additionalForm" label-width="220px" size="small">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="服务产生直接经济效益:" required>
                        <el-tooltip class="item" effect="dark" placement="top">
                          <div slot="content">营业收入、利润、生产成本、用工成本等效益总和</div>
                          <i class="el-icon-question mr5" style="color: #909399;"></i>
                        </el-tooltip>
                        <el-input-number
                          v-model="additionalForm.directEconomicBenefits"
                          :min="0"
                          :precision="2"
                          controls-position="right">
                        </el-input-number>
                        <span class="ml10">万元</span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="服务产生间接经济效益:" required>
                        <el-tooltip class="item" effect="dark" placement="top">
                          <div slot="content">能耗、环境污染、企业组织结构、管理、市场开拓、融资、安全、技术研发、员工专业技术能力、其他社会影响等所产生的效益总和</div>
                          <i class="el-icon-question mr5" style="color: #909399;"></i>
                        </el-tooltip>
                        <el-input-number
                          v-model="additionalForm.indirectEconomicBenefits"
                          :min="0"
                          :precision="2"
                          controls-position="right">
                        </el-input-number>
                        <span class="ml10">万元</span>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </div>
            <!-- 数字化转型产品附加信息 -->
            <div class="mt20" v-if="orderList[0]?.productDetail?.productTypeId === '33ac82ab-3ab4-46ce-bfd7-105fc62c4eac'">
              <div class="row-start-col-center">
                <div class="fs14 fwbold ml10">数字化转型附加信息</div>
              </div>
              <!-- 附加信息表单 -->
              <div class="pl20 pr20 pt20">
                <el-form ref="digitalTransformForm" :model="additionalForm" label-width="220px" size="small">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="数字化研发设计工具是否普及:" required>
                        <el-tooltip class="item" effect="dark" placement="top">
                          <div slot="content">指企业中应用数字化工具进行研发设计的比例。数字化研发设计工具指辅导企业开展产品设计，实现数字化建模、仿真、验证等功能的软件工具。对于离散型行业企业是指应用了二维或三维CAD，对于流程行业是指应用。</div>
                          <i class="el-icon-question mr5" style="color: #909399;"></i>
                        </el-tooltip>
                        <el-radio-group v-model="additionalForm.isDigitalRdToolSpread">
                          <el-radio :label="1">是</el-radio>
                          <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="关联工具数控化率:" required>
                        <el-tooltip class="item" effect="dark" placement="top">
                          <div slot="content">指企业在生产过程中，采用数控技术对关键工序进行自动化控制的比例。流程行业关键工序数控化率是指关键工序中过程控制系统（例如PLC、DCS、PCS等）的覆盖率；离散行业关键工序数控化率是指关键工序中数控系统（例如NC、DNC、CNC、FMC等）的覆盖率。</div>
                          <i class="el-icon-question mr5" style="color: #909399;"></i>
                        </el-tooltip>
                        <el-input-number
                          v-model="additionalForm.keyProcessCncRate" 
                          :min="0"
                          :max="100"
                          :precision="2"
                          controls-position="right">
                        </el-input-number>
                        <span class="ml10">%</span>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="数字化生成联网率:" required>
                        <el-tooltip class="item" effect="dark" placement="top">
                          <div slot="content">指已联网的数字化生产设备数量占全部数字化生产设备总数量的比例。目前所统计的已联网的数字化生产设备包括能与控制系统进行数据交换的数字化生产设备。</div>
                          <i class="el-icon-question mr5" style="color: #909399;"></i>
                        </el-tooltip>
                        <el-input-number
                          v-model="additionalForm.digitalProductionEquipmentNetworkingRate"
                          :min="0" 
                          :max="100"
                          :precision="2"
                          controls-position="right">
                        </el-input-number>
                        <span class="ml10">%</span>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="是否实现产业链协同:" required>
                        <el-tooltip class="item" effect="dark" placement="top">
                          <div slot="content">企业利用信息系统实现企业与其产业链上下游企业间在研发、采购、生产、销售、财务等关键业务协同运作。</div>
                          <i class="el-icon-question ml5" style="color: #909399;"></i>
                        </el-tooltip>
                        <el-radio-group v-model="additionalForm.digitalRdToolSpreadRate">
                          <el-radio :label="1">是</el-radio>
                          <el-radio :label="0">否</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>
              </div>
            </div>
          <!--          补贴兑付申请表单-->
          <div class="mt60">
            <div class="mb20 fwbold fs-md center">2025年服务券补贴兑付申请表单</div>
            <div class="width-24 tr fs-sm mb20 pr20">仅支持上传pdf文件。单个文件50M以内</div>
            <el-table v-loading="fileTableLoading" size="medium" :data="formList" border stripe :header-cell-style="{background:'rgb(252, 241, 231)',color:'#606266'}">
              <el-table-column type="index" label="序号" width="100px" align="center"></el-table-column>
              <el-table-column prop="fileTypeName" label="所需材料" align="center">
                <template slot-scope="{ row }">
                  <div style="margin-left:30px;text-align:left">
                       <span class="color-red" v-if="row.isNotnull">*</span><span>{{ row.fileTypeName }}</span>
                  </div>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="400px" align="center">
                  <template slot-scope="scope">
                    <div v-if="scope.row.isUpload == 0">
                      <upload-file v-if="detailStep === 0" :supportType="['pdf']" :disabled="detailStep !== 0" @setFileUrl="uploadRespond($event, scope.row)">点击上传</upload-file>
                    </div>
                    <div v-else class="row-start ml30">
                      <div v-if="detailStep === 0  && scope.row.fileName" class="mr10">{{scope.row.fileName}}</div>
                      <el-button v-else type="text" @click="openFile(scope.row)">点击查看</el-button>
                      <el-button v-if="detailStep === 0" circle size="mini" style="height:28px" icon="el-icon-delete" type="danger" @click="removeFile(scope.row)"></el-button>
                    </div>
                  </template>
              </el-table-column>
            </el-table>
            <div class="mt10 blue-text">
                <el-checkbox v-if="detailStep === 0" v-model="checked"><i class="el-icon-warning"></i> 
                      <span class="color-grey">提交申请前，请先阅读并同意</span>
                      <a :href="`${publicFileUrl}/real.html`" target="_blank">《真实性承诺》</a>
                </el-checkbox>
            </div>
          </div>
        </div>

        <div class="width-24 tc mt60 mb20">
          <el-button :disabled="!checked" :loading="submitLoading" v-if="formState !== 'view'"  @click="onSubmit" type="primary" size="medium">提交申请</el-button>
        </div>
      </div>
  </div>
</template>

<script>
import TimeLine from "@/components/timeLine";
import uploadFile from "@/components/upload/uploadFile";
import {getSubsidyDetail, getSubsidyFile, getSubsidyFileList, submitApply} from "@/api/homeApi";
import moment from 'moment';
export default {
  data() {
    return {
      moment,
      SubsidyApplyDetail: {
        status: 0,
        orderDetail: {
          orderId: "",
          productName: '',
          companyName: '',
          finishTime: '',
          price: '',
          discountPrice: '',
          status: 7
        }
      },
      orderList: [
        {
          orderId: "",
          productName: '',
          companyName: '',
          finishTime: '',
          price: '',
          discountPrice: '',
          status: 7,
          orderType: 1,
          totalPrice: 0
        }
      ],
      formList: [],
      formState: '',
      fileTableLoading: false,
      viewBtnLoading: false,
      submitLoading: false,
      subsidyId: '',
      checked:false,
      publicFileUrl:process.env.VUE_APP_PUBLIC_FILE_URL,
      detailStep: 0,
      additionalForm: {
        isDigitalRdToolSpread: 0,
        keyProcessCncRate: 0,
        digitalProductionEquipmentNetworkingRate: 0,
        digitalRdToolSpreadRate: 0,
        directEconomicBenefits: 0,
        indirectEconomicBenefits: 0
      },
      subsidyType: 0
    }
  },
  components: {
    TimeLine,
    uploadFile
  },
  computed: {
    // detailStep() {
    //    return this.SubsidyApplyDetail.status
    // }
  },
  mounted() {
    let query = this.$route.query
    this.formState = query?.type
    this.subsidyId = query?.subsidyId
    this.subsidyType = query?.subsidyType
    this.getPageDetail(query.orderId, query.subsidyId)
  },
  methods: {
    uploadRespond({fileId, fileName}, row) {
      this.$set(row, 'isUpload', 1)
      this.$set(row, 'fileId', fileId)
      this.$set(row, 'fileName', fileName)
    },
    removeFile(row) {
      this.$set(row, 'isUpload', 0)
      this.$set(row, 'fileId', '')
      this.$set(row, 'fileName', '')
    },
    openFile(row){
      getSubsidyFile({applyTypeFileId:row.applyTypeFileId,subsidyId :this.subsidyId}).then(res => {
        if (res.code === 200) {
           open(process.env.VUE_APP_BASE_API+`/public/file/v1/temp/get?token=${res.data.token}`)
        }
      })
    },
    async getPageDetail(orderId, subsidyId) {
      try {
        // 先获取兑付申请文件列表
        await this.getOrderFileList(subsidyId)
        // 等文件列表获取完成后，再获取兑付申请详情
        await this.getOrderDetail(orderId, subsidyId)
      } catch (error) {
        console.error('获取页面数据失败:', error)
        this.$message.error('获取页面数据失败')
      }
    },
    // 获取兑付申请详情
    getOrderDetail(orderId, subsidyId) {
      getSubsidyDetail({orderId, subsidyId}).then(res => {
        if (res.code === 200) {
          if (this.subsidyType === 1 && Array.isArray(res.data.subApplies)) {
            // 合并兑付类型
            this.SubsidyApplyDetail = Object.assign({}, res.data);
            this.orderList = res.data.subApplies.map(item => item.orderDetail);
          } else {
            this.SubsidyApplyDetail = Object.assign({}, res.data)
            this.orderList = [res.data.orderDetail]
          }
          // status:0 待审请 1-待审核 2-审核通过 3-审核不通过 4-退回修改
          if(res.data.status == 2 || res.data.status == 3){
            this.detailStep = 2
          } else if(res.data.status == 1 || res.data.status == 5){
            this.detailStep = 1
          } else {
            this.detailStep = 0
          }
          
          // 如果有附加信息，填充表单
          if (res.data.additionalInfo) {
            this.additionalForm = {
              ...this.additionalForm,
              ...res.data.additionalInfo
            }
          }
        }
      })
    },
    // 获取兑付申请文件列表
    getOrderFileList(subsidyId) {
      this.fileTableLoading = true
      getSubsidyFileList({subsidyId}).then(res => {
        if (res.code === 200) {
          this.formList = [...res.data]
        }
      }).finally(() => {
        this.fileTableLoading = false
      })
    },
    // 点击查看
    handleClick(row, index, type) {
      switch (type) {
        case 'view':
          this.getFileDownLoad(row, index)
          break;
        default:
          break;
      }
    },
    setFileUrl({fileId, fileName}, row) {
      this.$set(row, 'isUpload', true)
      this.$set(row, 'applyTypeFileId', fileId)
    },
    getFileDownLoad(row, index) {
      let self = this
      let query = this.$route.query
     self.viewBtnLoading = true
        getSubsidyFile({
          applyTypeFileId: row?.applyTypeFileId,
          baseFileName: row?.fileTypeName,
          subsidyId: query?.subsidyId
        }).then(res => {
          if (res.code === 200) {
            self.$message.success('下载成功，请点击文件查看！')
          } else {
            self.$message.error('下载文件失败!')
          }
        }).catch((error) => {
          self.$message.error('下载文件失败!')
        }).finally(() => {
          self.viewBtnLoading = false
        })
    },
    onSubmit() {
      let query = this.$route.query,
      self = this
      self.submitLoading = true

      // 准备附加信息
      let additionalInfo = {
        directEconomicBenefits: self.additionalForm.directEconomicBenefits,
        indirectEconomicBenefits: self.additionalForm.indirectEconomicBenefits
      };

      // 如果是数字化转型产品，添加特定字段
      if (self.orderList[0]?.productDetail?.productTypeId === '33ac82ab-3ab4-46ce-bfd7-105fc62c4eac') {
        additionalInfo = {
          ...additionalInfo,
          isDigitalRdToolSpread: self.additionalForm.isDigitalRdToolSpread,
          keyProcessCncRate: self.additionalForm.keyProcessCncRate,
          digitalProductionEquipmentNetworkingRate: self.additionalForm.digitalProductionEquipmentNetworkingRate,
          digitalRdToolSpreadRate: self.additionalForm.digitalRdToolSpreadRate
        };
      }

      // 提交申请
      submitApply({
        applyFileReqList: self.formList,
        subsidyId: query?.subsidyId,
        additionalInfo: additionalInfo
      }).then(res => {
        if (res.code === 200) {
          self.$message({
            type: 'success',
            duration: 2000,
            message: '提交成功！',
            onClose: () => {
              self.$router.back()
            }
          })
        }
      }).catch(() => {}).finally(() => {
        this.submitLoading = false
      })
    }
  },
}
</script>
<style scoped lang="scss">
@import "@/assets/css/element-variables";
p {
  margin: 0;
  padding: 0;
}
.card{
  margin: 0;
  padding: 0px 30px;
}
::v-deep.blue-text .el-checkbox__label {
  color: $text-color-blue ; /* Use !important to override default styles if necessary */
}
:deep(.el-step__title.is-success) {
   color: $text-color-blue;
 }

:deep(.el-step__head.is-success) {
  color: $text-color-blue;
  border-color: $text-color-blue;
}

:deep(.el-step__title.is-process) {
  color: $text-color-blue !important;
}

:deep(.el-step__head.is-success .el-step__line-inner) {
  // transition-delay: 0ms;
  border-width: 1px !important;
  width: 100% !important;
}

:deep(.el-step__head.is-process) {
  color: $text-color-blue;
  border-color: $text-color-blue;
}

:deep(.el-step__line-inner) {
  // border-style: dashed;
}

:deep(.el-step__title.is-process) {
  font-weight: 400;
  color: rgb(122, 121, 121);
}

:deep(.el-step__title.is-wait) {
  color: rgb(122, 121, 121);
}
</style>
